﻿
using HBase;
using HBase.cache;
using hCommand;
using hCommand.entity;
using System;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using hCommand.dto.wx;

namespace hCommand
{
    [RoutePrefix("api/recharge")]
    public class RechargeServer : BaseApiController {


        ISysServer sysServer = WMSDalFactray.getDal<ISysServer>();

        [HttpGet, Route("index")]
        public BaseResult index(String code) {

            BParam bp = sysServer.getById<BParam>(BaseConfig.BaseDBConnStr, 101);
            return BaseResult.Ok(bp);
        }
        [HttpGet, Route("open/{code}")]
        public BaseResult getOpenId(String code) {

            var url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + HttpHandler.appId
     + "&secret=ac3c54f7c0d6fe460ca048f23f011c0e&js_code=" + code + "&grant_type=authorization_code";
           var response= HttpRequestUrl.httpGet(url);
            JObject jsonObject = JsonConvert.DeserializeObject<JObject>(response);
            var id_ = jsonObject["openid"];
            if (id_ != null) {
                String id =id_ .ToString();
                return BaseResult.Ok(id);
            }
            return BaseResult.Ok("");

        }



        [HttpGet, Route("recharge/{openId}/{mony}")]
        public BaseResult recharge(string openId, int mony) {

            CyUser u = MyCache.getValue<CyUser>("User", openId);

            if (u == null) {
                return BaseResult.Error("用户异常");

            }
            string suffix = u.suffix;
            if (string.IsNullOrEmpty(suffix)) {
                return BaseResult.Error("用户分表异常");
            }

            string[] suffixArr = suffix.Split("@");
            if (suffixArr.Length != 2) {
                return BaseResult.Error("分表域异常");
            }
            string connStr = suffixArr[1];
            string suf = suffixArr[0];

            BParam bp = sysServer.getById<BParam>(BaseConfig.BaseDBConnStr, 101);
            Recharge re = new Recharge();
            re.id = WMSIdUtil.getId();
            re.userId = u.id;
            re.mony = mony;
            re.time = mony * (int)bp.v;
            re.status = 1;
            re.createTime = DateTime.Now;
            sysServer.insert(connStr, "Recharge" + suf, re);
            String res = "";
            String date = "{ \"appid\":\"wx5e4abb94037bfaac\", \"mchid\":\"1639883614\",\"description\":\""+ openId + "+充值"+mony+"\"," +
             "\"out_trade_no\":\"" + re.id + "\"," +
          "\"notify_url\":\"https://wx.szkuaijie.com/api/recharge/comfor\","
        + "\"amount\" :{\"total\":" + mony + ",\"currency\":\"CNY\"}, \"payer\":{\"openid\":\"" + openId + "\"}}";
            String taken = HttpHandler.SendAsync("/v3/pay/transactions/jsapi",date);
            var response = HttpRequestUrl.httpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi", date, taken) ;
            JObject jsonObject = JsonConvert.DeserializeObject<JObject>(response);
            String id = jsonObject["prepay_id"].ToString();
            

            RequestPayment rp=new RequestPayment(id); 
            return BaseResult.Ok(rp);
        }


        [HttpPost, Route("comfor")]
        public BaseResultAbs comfor([FromBody] ComforData data) {
            try
            {
                String dataInfo=data.resource.getDate();

                JObject jsonObject = JsonConvert.DeserializeObject<JObject>(dataInfo);
                String id_ = jsonObject["out_trade_no"].ToString();
                JObject payer = (JObject)jsonObject["payer"];
                long id = long.Parse(id_);
                String openId = payer["openid"].ToString();
                CyUser u = MyCache.getValue<CyUser>("User", openId);
                if (u == null)
                {
                    return HeadlessBaseResult.Error("用户异常");

                }
                string suffix = u.suffix;
                if (string.IsNullOrEmpty(suffix))
                {
                    return HeadlessBaseResult.Error("用户分表异常");
                }

                string[] suffixArr = suffix.Split("@");
                if (suffixArr.Length != 2)
                {
                    return HeadlessBaseResult.Error("分表域异常");
                }
                string connStr = suffixArr[1];
                string suf = suffixArr[0];
                Recharge re = sysServer.getById<Recharge>(connStr, "Recharge" + suf, id);
                if (re.status == 1) {
                    re.status = 5;
                    sysServer.update(connStr, "Recharge" + suf, re);
                }
          
                return HeadlessBaseResult.ok("true");
            } catch(Exception e){

                LoggerCommon.error("内部错误", e);
            }
            return HeadlessBaseResult.Error("内部错误");
        }



        [HttpGet, Route("his/{openId}/{size}")]
        public Page<Recharge> his(string openId, int size) {
            CyUser u = MyCache.getValue<CyUser>("User", openId);
            if (u == null) {
                return new Page<Recharge>();
            }
            string suffix = u.suffix;
            string[] suffArr = suffix.Split('@');
            PageDto dto = new PageDto() { pageSize = 20, pageNum = size };
            Page<Recharge> page = sysServer.queryPage<Recharge>(suffArr[1], "select * from Recharge" + suffArr[0] + " where status<>-1 and user_id='" + u.id + "'", " id  desc ", dto);
            return page;

        }


    }

   




 








}
